import os
import docx
from docx.shared import Pt, RGBColor
from docx.oxml.ns import qn
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT

def generate_project_documentation(project_path, output_file):
    # 创建Word文档
    doc = docx.Document()
    
    # 设置全局字体
    style = doc.styles['Normal']
    font = style.font
    font.name = 'Consolas'
    font.size = Pt(10)
    
    # 添加标题
    title = doc.add_heading('项目文档', 0)
    title.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
    
    # 添加项目路径
    doc.add_heading('项目路径:', level=1)
    doc.add_paragraph(project_path)
    
    # 添加项目结构
    doc.add_heading('项目结构:', level=1)
    structure = generate_directory_structure(project_path)
    doc.add_paragraph(structure)
    
    # 添加文件内容
    doc.add_heading('文件内容:', level=1)
    
    # 遍历项目目录
    for root, dirs, files in os.walk(project_path):
        # 排除的目录
        dirs[:] = [d for d in dirs if not should_ignore(d)]
        
        for file in files:
            if should_ignore(file):
                continue
                
            file_path = os.path.join(root, file)
            relative_path = os.path.relpath(file_path, project_path)
            
            # 添加文件路径标题
            doc.add_heading(relative_path, level=2)
            
            # 添加文件内容
            try:
                with open(file_path, 'r', encoding='utf-8') as f:
                    content = f.read()
                    # 创建代码段落
                    code_para = doc.add_paragraph()
                    code_para.add_run(content).font.name = 'Consolas'
            except Exception as e:
                doc.add_paragraph(f"无法读取文件: {str(e)}")
    
    # 保存文档
    doc.save(output_file)
    print(f"文档已生成: {output_file}")

def should_ignore(name):
    """判断是否应该忽略该文件/目录"""
    ignore_patterns = [
        '__pycache__', '.git', '.vscode', '.idea', 'venv', 'env',
        '.pytest_cache', 'node_modules', 'dist', 'build', '*.pyc',
        '.gitignore', '*.log', '*.tmp', '*.swp', '*.bak', 'Thumbs.db'
    ]
    
    # 检查是否匹配忽略模式
    for pattern in ignore_patterns:
        if pattern.startswith('*'):
            if name.endswith(pattern[1:]):
                return True
        elif name == pattern:
            return True
    return False

def generate_directory_structure(startpath):
    """生成目录树结构"""
    structure = []
    prefix = "│   "
    
    for root, dirs, files in os.walk(startpath):
        # 过滤忽略的目录
        dirs[:] = [d for d in dirs if not should_ignore(d)]
        files = [f for f in files if not should_ignore(f)]
        
        level = root.replace(startpath, '').count(os.sep)
        indent = "├── " if level > 0 else ""
        
        if level == 0:
            structure.append(os.path.basename(root))
        else:
            structure.append(f"{prefix * (level-1)}{indent}{os.path.basename(root)}")
        
        subindent = prefix * level + "├── "
        for i, file in enumerate(files):
            if i == len(files) - 1:
                subindent = prefix * level + "└── "
            structure.append(f"{subindent}{file}")
    
    return "\n".join(structure)

if __name__ == "__main__":
    project_path = r"D:\code\git\siwanmaoxi\pyproject"
    output_file = r"D:\code\git\siwanmaoxi\project_documentation.docx"
    
    generate_project_documentation(project_path, output_file)